package com.googlecode.esblabs.util.io;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;

public class WriterOutputStream extends OutputStream {

	private String encoding = null;
	private Writer writer = null;

	public WriterOutputStream(Writer writer) {
		this.writer = writer;
	}

	public WriterOutputStream(Writer writer, String encoding) {
		this.encoding = encoding;
		this.writer = writer;
	}

	public void write(int aByte) throws IOException {
		write((byte)aByte);
	}

	public void write(byte[] bytes) throws IOException {
		if (encoding == null) {
			writer.write(new String(bytes));
		} else{
			writer.write(new String(bytes, encoding));
		}
	}

	public void write(byte[] bytes, int offset, int length) throws IOException {
		if (encoding == null) {
			writer.write(new String(bytes, offset, length));
		} else {
			writer.write(new String(bytes, offset, length, encoding));
		}
	}

	public void flush() throws IOException {
		writer.flush();
	}

	public void close() throws IOException {
		writer.close();
		resetState();
	}

	private void resetState() {
		encoding = null;
		writer = null;
	}
}